<?php

declare(strict_types=1);



namespace App\Controller;

use App\Constants\ErrorCode;
use App\Traits\QiniuTraits;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Qiniu\Storage\UploadManager;


class QNFileController extends AbstractController
{
    use QiniuTraits;
    // upload
    public function upload(RequestInterface $request)
    {
        $config = config('qiniu.huadong');
        $auth = $this->auth();
        // 生成上传Token
        $token = $auth->uploadToken($config['czhtest001']);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        $path = config('upload_path');
        if (file_exists($path.'/timg.jpg') ) {
            list($ret, $err)   = $uploadMgr->putFile($token, 'timg.jpg', $path.'/timg.jpg');
            if ($this->checkResponse($ret, $err)) {
                return $this->response->json([
                    'msg' => '上传成功',
                    'code' => ErrorCode::SUCCESS,
                ]);
            }
            $msg = '上传失败';
        } else {
            $msg = '文件不存在';
        }
        return $this->response->json([
            'msg' => $msg,
            'code' => ErrorCode::SERVER_ERROR,
        ]);
    }

    // getFile
    public function getFile(RequestInterface $request) {
        $key = $request->input('key');
        return $this->response->json([
            'data' => $this->load($key),
            'code' => ErrorCode::SERVER_ERROR,
        ]);
    }
}
